<template>
  <div class="app-container">
    <!-- 操作 -->
    <div class="crud">
      <div class="crud-left">
        <el-button v-if="role_list.indexOf('80000090101') != -1" class="fill-btn" @click="handleUpdate(-1, 'create')">添加
        </el-button>
        <el-button v-if="role_list.indexOf('80000090103') != -1" class="plain-btn" @click="handleDelmultip">删除
        </el-button>
        <el-button class="plain-btn reset-btn" @click="resetfilter">重置</el-button>
        <div class="input-box">
          <span class="item-label">所属地区</span>
          <addr-select class="address-select" select_level="0" @changenode="changeAddr" ref="parent_cascader"></addr-select>
        </div>
        <div class="input-box">
          <span class="item-label">所属公司</span>
          <el-select class="group-select" v-model="listQuery.groupId" filterable reserve-keyword placeholder="选择公司"
            @change="changeGroup" clearable>
            <el-option v-for="item in list_group" :key="item.id" :label="item.label" :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="input-box">
          <span class="item-label">所属网点</span>
          <el-select class="branch-select" v-model="listQuery.deptId" filterable reserve-keyword placeholder="绑定网点"
            @change="changeBranch" clearable>
            <el-option v-for="item in list_branch" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </div>
      </div>

      <div class="search">
        <el-input v-model="listQuery.keyword" placeholder="查找用户" class="crud-input">
          <el-button class="search-btn" slot="append" icon="el-icon-search" @keyup.enter.native="handleFilter"
            @click="handleFilter" />
        </el-input>
      </div>
    </div>

    <!-- 0 table表格 -->
    <el-form ref="UserManagementFrom" :model="UserManagementFrom" :rules="rules">
      <el-table :key="tableKey" v-loading="listLoading" element-loading-text="数据加载中"
        element-loading-spinner="el-icon-loading" :data="UserManagementFrom.list" border fit highlight-current-row
        style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号">
        </el-table-column>

        <el-table-column label="真实姓名" align="center" prop="realName" width="150">
          <template slot-scope="{ row, $index }">
            <el-form-item v-if="row.edit_inline" :prop="'list.' + $index + '.realName'" :rules="rules.realName">
              <el-input v-model="row.realName" class="edit-input" size="small" />
            </el-form-item>
            <span v-else>{{ row.realName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名" align="center" prop="name" width="230">
          <template slot-scope="{ row, $index }">
            <el-form-item v-if="row.edit_inline" :prop="'list.' + $index + '.name'" :rules="rules.name">
              <el-input v-model="row.name" class="edit-input" size="small" />
            </el-form-item>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="250" align="center" prop="HArole">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <el-select v-model="row.roleIds" filterable reserve-keyword placeholder="角色资源分配" style="width: 100%" multiple clearable >
                <el-option v-for="item in row.list_role_temp" :key="item.roleId" :label="item.roleName" :value="item.roleId" :disabled="item.disable"/>
              </el-select>
            </el-form-item>
            <div v-else>
              <el-tag class="show-tag" type="primary" v-for="val in row.roles" :key='val.roleId' size="mini">{{val.roleName}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="网点资源权限" min-width="300" align="center" prop="HAnetwork">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <el-select v-model="row.branchIds" filterable reserve-keyword placeholder="网点资源分配" style="width: 100%" multiple clearable >
                <el-option v-for="item in row.list_resource2_temp" :key="item.resGroupId" :label="item.resGroupName" :value="item.resGroupId" :disabled="item.disable"/>
              </el-select>
            </el-form-item>
            <div v-else>
              <el-tag class="show-tag" type="primary" v-for="val in row.pointResGroups" :key='val.resGroupId' size="mini">{{val.resGroupName}}</el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="设备资源权限" min-width="300" align="center" prop="HAequipment">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <el-select v-model="row.deviceIds" filterable reserve-keyword placeholder="设备资源分配" style="width: 100%" multiple clearable >
                <el-option v-for="item in row.list_resource1_temp" :key="item.resGroupId" :label="item.resGroupName" :value="item.resGroupId" :disabled="item.disable"/>
              </el-select>
            </el-form-item>
            <div v-else>
              <el-tag class="show-tag" type="primary" v-for="val in row.deviceResGroups" :key='val.resGroupId' size="mini">{{val.resGroupName}}</el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="注册手机号" min-width="130" align="center" prop="phone">
          <template slot-scope="{ row, $index }">
            <el-form-item v-if="row.edit_inline" :prop="'list.' + $index + '.phone'" :rules="rules.phone">
              <el-input v-model="row.phone" class="edit-input" size="small" />
            </el-form-item>
            <span v-else>{{ row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属网点" min-width="140px" align="center" prop="deptId">
          <template slot-scope="{ row, $index }">
            <el-form-item v-if="row.edit_inline" :prop="'list.' + $index + '.deptId'" :rules="rules.deptId">
              <el-select v-model="row.deptId" filterable reserve-keyword placeholder="选择网点" style="width: 100%"
                clearable>
                <el-option v-for="item in list_branch" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <!-- <span v-else>{{ row.deptId }}</span> -->
            <span v-else>{{ row.deptName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="300" show-overflow-tooltip align="center">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <div class="temp-input">
                <el-input v-model="row.remark" class="edit-input" size="small" :maxlength="60" type="textarea"
                  placeholder="请输入内容" show-word-limit />
              </div>
            </el-form-item>
            <span v-else>{{ row.remark }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="所属公司" min-width="140px"  align="center">
        <template slot-scope="{row}">
          <span>{{ group_name(row.groupId) }}</span>
        </template>
      </el-table-column> -->

        <!-- <el-table-column label="状态" class-name="status-col" width="150">
        <template slot-scope="{row}">
          <el-switch v-model="row.isOnline" active-color="#00805a" inactive-color="#B0B7C9" active-text="正常"
            inactive-text="禁用" :active-value="1" :inactive-value="0" @change="changeStatus(row)" />
        </template>
      </el-table-column> -->
        <el-table-column label="创建时间" prop="createTime" sortable min-width="130" align="center">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <span>{{
                row.createTime | parseTime("{y}-{m}-{d} {h}:{i}")
              }}</span>
            </el-form-item>
            <span v-else>{{
              row.createTime | parseTime("{y}-{m}-{d} {h}:{i}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="末次登录" min-width="130" align="center">
          <template slot-scope="{ row }">
            <el-form-item v-if="row.edit_inline">
              <span>{{
                row.updateTime | parseTime("{y}-{m}-{d} {h}:{i}")
              }}</span>
            </el-form-item>
            <span v-else>{{
              row.updateTime | parseTime("{y}-{m}-{d} {h}:{i}")
            }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="100px" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{ row }">
            <template v-if="row.edit_inline">
              <span v-if="row.edit_inline" class="action action-update" @click="cancelEditLine(row)">取消</span>
              <span> | </span>
              <span v-if="row.edit_inline" class="action action-update" @click="updateDataInline(row)">保存</span>
            </template>
            <span v-else-if="role_list.indexOf('80000090102') != -1" class="action action-update"
              @click="inlineEdit(row)">编辑</span>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!-- 1 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 2 添加或修改的弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" width="60%" :close-on-click-modal="false" center>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="90px">
        <div class="formitem-container">
          <el-form-item prop="deptId">
            <span slot="label" class="form-item-label">所属网点</span>
            <addr-branch :select_level="1" @changenode="handleAddr" />
          </el-form-item>

          <el-form-item prop="name" label="登录名">
            <span slot="label" class="form-item-label">登录名</span>
            <el-input v-model="temp.name" type="text" maxlength="18" placeholder="请输入登录名" clearable />
          </el-form-item>
          <el-form-item prop="realName" label="姓名">
            <span slot="label" class="form-item-label">姓名</span>
            <el-input v-model="temp.realName" type="text" maxlength="18" placeholder="请输入姓名" clearable />
          </el-form-item>

          <el-tooltip v-model="reg_tooltip" content="打开了大写!" placement="right" manual>
            <el-form-item prop="password" label="密码">
              <span slot="label" class="form-item-label">密码</span>
              <el-input :key="password_type_reg" ref="password_reg" v-model="temp.password" :type="password_type_reg"
                placeholder="用户密码" name="password_reg" tabindex="6" autocomplete="off" clearable
                @keyup.native="checkCapslock(0, $event)" @blur="reg_tooltip = false">
                <span slot="append" class="show-pwd" @click="showPwd(0)">
                  <svg-icon :icon-class="
                      password_type_reg === 'password' ? 'eye' : 'eye-open'
                    " />
                </span>
              </el-input>
            </el-form-item>
          </el-tooltip>
          <el-tooltip v-model="reg2_tooltip" content="打开了大写!" placement="right" manual>
            <el-form-item prop="again_pass" label="确认密码">
              <span slot="label" class="form-item-label">确认密码</span>
              <el-input :key="password_type_reg2" ref="password_reg2" v-model="temp.again_pass"
                :type="password_type_reg2" placeholder="请再次输入密码" name="password_reg2" tabindex="6" autocomplete="off"
                clearable @keyup.native="checkCapslock(1, $event)" @blur="reg2_tooltip = false">
                <span slot="append" class="show-pwd" @click="showPwd(1)">
                  <svg-icon :icon-class="
                      password_type_reg2 === 'password' ? 'eye' : 'eye-open'
                    " />
                </span>
              </el-input>
            </el-form-item>
          </el-tooltip>

          <el-form-item prop="email" label="邮箱">
            <span slot="label" class="form-item-label">邮箱</span>
            <el-input v-model="temp.email" type="text" maxlength="18" placeholder="邮箱" clearable />
          </el-form-item>
          <el-form-item prop="phone" label="手机号">
            <span slot="label" class="form-item-label">手机号</span>
            <el-input v-model="temp.phone" type="text" maxlength="18" placeholder="手机号" clearable />
          </el-form-item>
          <el-form-item label="备注">
            <span slot="label" class="form-item-label">备注</span>
            <el-input v-model="temp.remark" type="text" maxlength="60" placeholder="备注" clearable />
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="dialogFormVisible = false">取消</el-button>
        <el-button class="fill-dialog-btn" @click="dialogStatus === 'create' ? createData() : updateData()">确认
        </el-button>
      </div>
    </el-dialog>
    <!-- 3 删除的提示框 -->
    <el-dialog :visible.sync="dialogPvVisible" title="提示" width="30%" center>
      <div class="del-data del-img">
        <img :src="require('../../assets/img/del.png')" alt="" />
      </div>
      <div class="del-data del-notify">确定对用户进行【删除】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="dialogPvVisible = false">取消</el-button>
        <el-button class="fill-dialog-btn" @click="delData">确认</el-button>
      </span>
    </el-dialog>
    <!-- 4 状态更改的提示框 -->
    <el-dialog :visible.sync="dialogToggle" title="提示" width="30%" center>
      <div class="del-data del-img">
        <img :src="require('../../assets/img/remind.png')" alt="" />
      </div>
      <div class="del-data del-notify">确定对状态进行【更改】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="plain-dialog-btn" @click="handleCancel(sta_row)">取消</el-button>
        <el-button class="fill-dialog-btn" @click="toggleStatus(sta_row)">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import waves from "@/directive/waves"; // waves directive
  import {
    parseTime
  } from "@/utils"; // 解析时间
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import AddrSelect from "@/components/Address/AddrSelect";
  import AddrBranch from "@/components/Address/AddrBranchSelect.vue";

  import {
    userAdd,
    userDel,
    userUpdate,
    userList,
    userDetail,
    userResetpass,
    userSelectRole,
    userRoles,
    resourceList,
  } from "@/api/permission";
  import {
    branchCpidList,
    branchList
  } from "@/api/branch";

  import {
    validMobile,
    validPass,
    validUser,
    validEmail,
    validRealname,
  } from "@/utils/validate";

  const calendarTypeOptions = [{
      key: "CN",
      display_name: "China"
    },
    {
      key: "US",
      display_name: "USA"
    },
    {
      key: "JP",
      display_name: "Japan"
    },
    {
      key: "EU",
      display_name: "Eurozone"
    },
  ];

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name;
    return acc;
  }, {});

  export default {
    name: "PermissionUser",
    components: {
      Pagination,
      AddrSelect,
      AddrBranch
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: "success",
          draft: "info",
          deleted: "danger",
        };
        return statusMap[status];
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type];
      },
    },
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!validUser(value)) {
          callback(new Error("3 - 16位,只含字母和数字,非数字开头."));
        } else {
          callback();
        }
      };
      const validateEmail = (rule, value, callback) => {
        if (!validEmail(value)) {
          callback(new Error("邮箱格式不正确"));
        } else {
          callback();
        }
      };
      const validateMobile = (rule, value, callback) => {
        if (!validMobile(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      };

      const validatePassword = (rule, value, callback) => {
        if (!validPass(value)) {
          callback(new Error("6~16位,大小写字母和数字, 可以有特殊字符"));
        } else {
          callback();
        }
      };
      // 新增真实姓名校验
      const validateRealname = (rule, value, callback) => {
        if (!validRealname(value)) {
          callback(new Error("2 - 6位, 不含数字和字母"));
        } else {
          callback();
        }
      };

      return {
        yyy: [],
        multipleSelection: [],
        is_multip: false, // 是否批量删除
        tableKey: 0,
        // list: null,
        UserManagementFrom: {
          list: [],
        },
        total: 0, // 总条数
        listLoading: false,
        listQuery: {
          page: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: "", // 搜索关键字
          groupId: "", // 公司种类
          node_code: "", // 地区节点id
          deptId: "", // 网点id
          level: "", // node 的等级
          provinceCode: "",
          cityCode: "",
          areaCode: "",
          streetCode: "",
        },
        calendarTypeOptions,
        tempInline: {
          roleIds: [],
          roleIds: [],
          roleIds: [],
        },
        temp: {
          deptId: "", // 网点id
          email: "", // 邮箱
          idCard: "", // 身份证
          name: "", // 名字
          password: "",
          again_pass: "",
          phone: "", // 手机号
          policeCode: "", //
          realName: "", // 真实名字
          remark: "", // 备注
          roleIds: [], // 角色id
          groupId: "", // 组id
          parentId: "", // 上级id
          shortLetter: "", //
          userCode: "", //
          branchIds: [], //
          deviceIds: [], //
          resourceGroupIds: [],
        },
        sta_row: {}, // 修改状态值, 保存当前数据
        dialogFormVisible: false,
        dialogStatus: "",
        del_id: "",
        del_index: null,
        dialogPvVisible: false, // 删除提示框
        dialogToggle: false, // 状态更改的提示框
        rules: {
          password: [{
            required: true,
            trigger: "blur",
            validator: validatePassword
          }, ],
          again_pass: [{
            required: true,
            trigger: "blur",
            validator: validatePassword
          }, ],
          name: [{
            required: true,
            trigger: "blur",
            validator: validateUsername
          }, ],
          email: [{
            required: true,
            trigger: "blur",
            validator: validateEmail
          }],
          phone: [{
            required: true,
            trigger: "blur",
            validator: validateMobile
          }],
          // 真实姓名和网点校验
          realName: [{
            required: true,
            trigger: "blur",
            validator: validateRealname
          }, ],
          deptId: [{
            required: true,
            message: "请选择网点",
            trigger: "change"
          }],
          // 新加的行内编辑校验
          HArole: [{
            required: true,
            message: "角色不能为空",
            trigger: "change"
          }, ],
          HAnetwork: [{
            required: true,
            message: "网点资源权限不能为空",
            trigger: "change",
          }, ],
          HAequipment: [{
            required: true,
            message: "设备资源权限不能为空",
            trigger: "change",
          }, ],
        },
        list_group: [{
            id: "",
            label: "全部"
          },
          {
            id: 11,
            label: "邮政"
          },
          {
            id: 12,
            label: "圆通"
          },
          {
            id: 13,
            label: "申通"
          },
          {
            id: 14,
            label: "中通"
          },
          {
            id: 15,
            label: "韵达"
          },
          {
            id: 16,
            label: "顺丰"
          },
        ], // 所属公司
        list_branch: [],   // 所属网点
        list_role: [],   // 角色列表
        branch_name: "",
        dept_id: "", // 点击第二侧边栏, 保存的网点ID
        list_resource: [],
        list_resource1: [],
        list_resource2: [],

        password_type_reg: "password",
        password_type_reg2: "password",
        reg_tooltip: false, // 大写 ?
        reg2_tooltip: false, // 大写 ?
        role_list: [], // 按钮权限
      };
    },
    watch: {},
    created() {
      this.getList();
    },
    mounted() {
      this.getBranchList();
      this.getRoleList();
      this.getResourceList();
      this.role_list = this.$store.getters.menu_code_list;
    },
    computed: {
      group_name() {
        return (groupId) => {
          if (groupId == 11) return "邮政";
          else if (groupId == 12) return "圆通";
          else if (groupId == 13) return "申通";
          else if (groupId == 14) return "中通";
          else if (groupId == 15) return "韵达";
          else if (groupId == 16) return "顺丰";
        };
      },
    },
    methods: {
      // 获取 table 列表
      getList() {
        this.listLoading = true;
        let temp_query = {
          pageNo: this.listQuery.page,
          pageSize: this.listQuery.limit,
          searchInfo: this.listQuery.keyword,
          include: 0,
          groupId: this.listQuery.groupId,
          deptId: this.listQuery.deptId,
        };
        if (this.listQuery.level == 1)
          temp_query.provinceCode = this.listQuery.provinceCode;
        else if (this.listQuery.level == 2)
          temp_query.cityCode = this.listQuery.cityCode;
        else if (this.listQuery.level == 3)
          temp_query.areaCode = this.listQuery.areaCode;
        else if (this.listQuery.level == 4)
          temp_query.streetCode = this.listQuery.streetCode;

        userList(temp_query)
          .then((res) => {
            if (res.code == 0) {
              this.UserManagementFrom.list = res.list;
              this.total = parseInt(res.total);
              this.UserManagementFrom.list = this.UserManagementFrom.list.map(
                (item, i) => {
                  item.roleIds = []
                  item.branchIds = []
                  item.deviceIds = []
                  this.$set(item, "edit_inline", false);
                  item.original_deptId = item.deptId;
                  // item.original_email = item.email
                  item.original_name = item.name;
                  // item.original_password = item.password
                  item.original_phone = item.phone;
                  item.original_realName = item.realName;
                  item.original_remark = item.remark;
                  // item.original_groupId = item.groupId
                  // userRoles({userId: item.id}).then(res => {
                  //   this.$set(item, 'roleIds_obj', res.data)
                  //   let arr = []
                  //   if(item.roleIds_obj) {
                  //     item.roleIds_obj.forEach((item, i) => {
                  //       arr.push(item.id)
                  //     })
                  //   }
                  //   this.$set(item, 'roleIds', arr)
                  // })
                  return item;
                }
              );
              this.listLoading = false;
            } else {
              this.$message({
                message: "请求失败",
                type: "error",
              });
            }
          })
          .catch((res) => {
            this.listLoading = false;
          });
      },
      // 点击行内编辑
      inlineEdit(row) {
        console.log(row)
        row.edit_inline = !row.edit_inline
        this.inlineEditRole(row)
        this.inlineEditBranch(row)
        this.inlineEditDevice(row)
      },
      inlineEditRole(row) {
        row.list_role_temp = [...this.list_role]
        if(row.roles) row.roles.map((val, index2) => {
          let flag = true
          this.list_role.forEach((val2, index3) => {
            if(val.roleId == val2.roleId) {   // 两数组均有
              flag = false
              row.roleIds.push(val2.roleId)
            }
          })
          if(flag) {   // 当前登录者没有的 角色组
            row.list_role_temp.push({roleId: val.roleId, roleName: val.roleName, disable: true})
            row.roleIds.push(val.roleId)
          }

        })
      },
      inlineEditBranch(row) {
        row.list_resource2_temp = [...this.list_resource2]
        
        if(row.pointResGroups) row.pointResGroups.map((val, index2) => {
          let flag = true
          this.list_resource2.forEach((val2, index3) => {
            if(val.resGroupId == val2.resGroupId) {   // 两数组均有
              flag = false
              row.branchIds.push(val2.resGroupId)
            }
          })
          if(flag) {   // 当前登录者没有的(网点资源组)
            row.list_resource2_temp.push({roleId: val.resGroupId, roleName: val.resGroupName, disable: true})
            row.branchIds.push(val.resGroupId)
          }

        })
      },
      inlineEditDevice(row) {
        row.list_resource1_temp = [...this.list_resource1]
        
        if(row.deviceResGroups) row.deviceResGroups.map((val, index2) => {
          let flag = true
          this.list_resource1.forEach((val2, index3) => {
            if(val.resGroupId == val2.resGroupId) {   // 两数组均有
              flag = false
              row.deviceIds.push(val2.resGroupId)
            }
          })
          if(flag) {   // 当前登录者没有(设备资源组)
            row.list_resource1_temp.push({roleId: val.resGroupId, roleName: val.resGroupName, disable: true})
            row.deviceIds.push(val.resGroupId)
          }

        })
      },

      // 重置按钮---------------
      resetfilter() {
        this.listQuery = {
          page: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: "", // 搜索关键字
          groupId: "", // 公司种类
          node_code: "", // 地区节点id
          deptId: "", // 网点id
          level: "", // node 的等级
          provinceCode: "",
          cityCode: "",
          areaCode: "",
          streetCode: "",
        };
        this.$refs["parent_cascader"].clearNodes();
        this.getList();
      },

      // 获取当前区域的网点列表( 下拉回显)
      getBranchList() {
        branchList().then((res) => {
          if (res.code == 0) {
            this.list_branch = res.data || [];
          }
        });
      },

      // 获取角色列表 (下拉回显)
      getRoleList() {
        userSelectRole().then((res) => {
          let tempList = res.data || []
          this.list_role = []
          tempList.forEach((item) => {
            this.list_role.push({roleId: item.id, roleName: item.name, disable: false})
          })
        });
      },
      // 获取资源组列表 (下拉回显)
      getResourceList() {
        resourceList().then((res) => {
          this.list_resource = res.data || [];
          this.list_resource.forEach((item) => {
            if(item.groupType == 2) {
              this.list_resource2.push({resGroupId: item.id, resGroupName: item.name, disable: false})
            }
            else if(item.groupType == 1) {
              this.list_resource1.push({resGroupId: item.id, resGroupName: item.name, disable: false})
            }
          })
          

          // this.list_resource2 = this.list_resource.filter((item) => {
          //   return item.groupType == 2;
          // });
          // this.list_resource1 = this.list_resource.filter((item) => {
          //   return item.groupType == 1;
          // });
        });
      },

      // 取消当行编辑
      cancelEditLine(row, is_cancel = true) {
        row.deptId = row.original_deptId;
        // row.email = row.original_email
        row.idCard = row.original_idCard;
        row.name = row.original_name;
        // row.password = row.original_password
        row.phone = row.original_phone;
        row.realName = row.original_realName;
        row.remark = row.original_remark;
        // row.groupId = row.original_groupId

        row.edit_inline = false;
        if (is_cancel) {
          this.$message({
            message: "已经取消更改",
            type: "warning",
          });
        }
      },
      // 行内编辑提交更新请求
      updateDataInline(row) {
        this.$refs["UserManagementFrom"].validate((valid) => {
          if (valid) {
            row.resourceGroupIds = [
              ...row.deviceIds,
              ...row.branchIds,
            ];
            userUpdate(row)
              .then((res) => {
                if (res.code == 0) {
                  // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
                  // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
                  this.getList();
                  // this.resetfilter()
                  row.edit_inline = false;
                  this.$notify({
                    title: "成功",
                    message: "更新成功",
                    type: "success",
                    duration: 4000,
                  });
                } else {
                  this.cancelEditLine(row, false);
                  this.$message({
                    message: "更改失败",
                    type: "error",
                  });
                }
              })
              .catch((res) => {
                this.cancelEditLine(row, false);
                this.$message({
                  message: "更改失败!",
                  type: "error",
                });
              });
          }
        });
      },

      // 点击了 状态值切换==========================
      changeStatus(row) {
        this.dialogToggle = true;
        this.sta_row = row;
      },
      // 确认了  状态值切换
      toggleStatus(row) {
        deviceStatus({
            deviceId: row.id,
            status: row.isOnline
          })
          .then((res) => {
            this.$notify({
              title: "成功",
              message: "状态修改成功",
              type: "success",
              duration: 4000,
            });
            this.dialogToggle = false;
          })
          .catch((res) => {
            this.cancelEditLine(row);
            this.$message({
              message: "网络错误",
              type: "error",
            });
          });
      },
      // 取消状态管理
      handleCancel(row) {
        this.cancelEditLine(row);
        this.dialogToggle = false;
      },

      // 监听是否打开了大写
      checkCapslock(num, e) {
        const {
          key
        } = e;
        if (num == 0) {
          // 注册账号: 设置密码
          this.reg_tooltip = key && key.length === 1 && key >= "A" && key <= "Z"; // 若开启大写则提示文字
        } else if (num == 1) {
          // 注册账号: 再次输入密码
          this.reg2_tooltip = key && key.length === 1 && key >= "A" && key <= "Z"; // 若开启大写则提示文字
        }
      },
      // 是否显示密码
      showPwd(num) {
        if (num == 0) {
          this.password_type_reg === "password" ?
            (this.password_type_reg = "") :
            (this.password_type_reg = "password");
          this.$nextTick(() => {
            // 待Dom更新完毕 获取到输入框焦点
            this.$refs.password_reg.focus();
          });
        } else if (num == 1) {
          this.password_type_reg2 === "password" ?
            (this.password_type_reg2 = "") :
            (this.password_type_reg2 = "password");
          this.$nextTick(() => {
            // 待Dom更新完毕 获取到输入框焦点
            this.$refs.password_reg2.focus();
          });
        }
      },

      // 点击了 '编辑' 或添加======================================================
      handleUpdate(row, str) {
        if (str == "create") this.resetTemp(); // 清空
        if (str == "update") {
          this.temp = Object.assign({}, row); // 克隆一个对象
        }
        this.dialogStatus = str;

        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      },
      // 编辑: 确认更新数据
      updateData() {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            if (this.temp.password != this.temp.again_pass) {
              this.$message({
                message: "密码不一致",
                type: "error",
              });
            } else {
              userUpdate(this.temp).then(() => {
                // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
                // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
                this.getList();
                this.dialogFormVisible = false;
                this.$notify({
                  title: "成功",
                  message: "更新成功",
                  type: "success",
                  duration: 4000,
                });
              });
            }
          } else {
            return false;
          }
        });
      },
      // 确认添加
      createData() {
        this.$refs["dataForm"].validate((valid) => {
          if (valid) {
            if (this.temp.password != this.temp.again_pass) {
              this.$message({
                message: "密码不一致",
                type: "error",
              });
            } else {
              let data = Object.assign({}, this.temp);
              const cryptograph = this.$sha256(this.temp.password + "dawk"); // 给密码加密
              data.password = cryptograph;
              data.again_pass = cryptograph;
              userAdd(data)
                .then((res) => {
                  if(res.code == 0) {
                    // this.list.unshift(this.temp)
                    this.getList();
                    // this.resetfilter()
                    this.dialogFormVisible = false;
                    this.$notify({
                      title: "成功",
                      message: "添加成功",
                      type: "success",
                      duration: 4000,
                    });
                  }
                  else if(res.code == -4) {
                    if(res.msg.split(' ')[0] == 'name') {
                      this.$message({
                        message: '登录名已经存在',
                        type: 'error'
                      })
                    }
                    else if(res.msg.split(' ')[0] == 'email') {
                      this.$message({
                        message: '邮箱已经存在',
                        type: 'error'
                      })
                    }
                    else if(res.msg.split(' ')[0] == 'phone') {
                      this.$message({
                        message: '手机号已经存在',
                        type: 'error'
                      })
                    }
                  }
                  else {
                    this.$message({
                      message: "添加失败",
                      type: "error",
                    });
                  }
                })
                .catch((res) => {
                  this.$message({
                    message: "网络错误",
                    type: "error",
                  });
                });
            }
          } else {
            return false;
          }
        });
      },
      // 清空temp
      resetTemp() {
        this.temp = {
          deptId: "", // 网点id
          email: "", // 邮箱
          idCard: "", // 身份证
          name: "", // 名字
          parentId: "", // 上级id
          password: "",
          again_pass: "",
          phone: "", // 手机号
          policeCode: "", //
          realName: "", // 真实名字
          remark: "", // 备注
          roleIds: [], // 角色id
          shortLetter: "", //
          userCode: "", //
          groupId: 11,   // 公司id
          branchIds: [],   // 网点ID
          deviceIds: [],   // 设备ID
          resourceGroupIds: [],
        };
      },
      // 点击了删除===============================================
      handleDelete(row, index) {
        this.is_multip = false;
        this.del_id = row.id;
        this.del_index = index;
        this.dialogPvVisible = true;
      },
      // 点击了 批量删除
      handleDelmultip() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: "没有被选项!",
            type: "error",
            duration: 4000,
            showClose: true,
            center: true,
          });
        } else {
          this.is_multip = true;
          this.dialogPvVisible = true;
        }
      },
      // 确认了删除
      delData() {
        let ids = [];
        if (this.is_multip) {
          // 批量删
          this.multipleSelection.forEach((item, i) => {
            ids.push(item.id);
          });
        } else {
          ids = [this.del_id];
        }
        userDel(ids).then(() => {
          this.dialogPvVisible = false;
          // this.list.splice(this.del_index, 1)
          this.getList();
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 4000,
          });
        });
      },

      // 筛选条件的切换 (地区切换)
      changeAddr(cut_node, cut_level, newval) {
        if (cut_level == 1) {
          this.listQuery.provinceCode = cut_node;
          this.listQuery.level = cut_level;
        } else if (cut_level == 2) {
          this.listQuery.cityCode = cut_node;
          this.listQuery.level = cut_level;
        } else if (cut_level == 3) {
          this.listQuery.areaCode = cut_node;
          this.listQuery.level = cut_level;
        } else if (cut_level == 4) {
          this.listQuery.streetCode = cut_node;
          this.listQuery.level = cut_level;
        }
        this.getList();
      },

      // 筛选条件的切换 (公司切换)
      changeGroup() {
        this.getList();
      },
      // 帅选条件的切换 (网点切换)
      changeBranch() {
        this.getList();
      },
      // 搜索
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      // 批量选择
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 添加用户时:  选择网点
      handleAddr(code, level, newval) {
        this.temp.deptId = code;
      },
    },
  };
</script>

<style lang="scss">
  @import "~@/styles/variables.scss";

  .crud {
    // .el-input-group__append {
    //   color: var(--app_primary);
    //   border: 0;
    //   border-left: 1px solid var(--app_primary);

    //   .el-button {
    //     // height: 27px;
    //     // border: 1px solid $my_primary !important;
    //     // background-color: #f11;
    //   }
    // }
  }

  .el-dialog {
    .el-dialog__header {
      background-color: #f5f7f5 !important;
    }
  }

  .formitem-container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .el-form-item {
      width: 49%;
      margin-bottom: 25px;
    }
  }

  .el-form-item__label {
    // 两端对齐
    display: flex;
    justify-content: space-between;
    align-items: center !important;

    &::before {
      transform: translateY(3px);
    }

    .form-item-label {
      flex: 1;
      text-align-last: justify !important;
      text-align: justify !important;
    }
  }
</style>


<style lang="scss" scoped>
  @import "~@/styles/variables.scss";

  .app-container {
    padding: 10px;
    background-color: #ffffff;

    .crud {
      // background-color: blanchedalmond;
      margin-bottom: 32px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .crud-left {
        // background-color: #faa;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .reset-btn {
          margin-right: 15px;
        }
      }
    }

    // background-color: #f99 !important;
    .el-table {
      .action {
        font-size: 13px;
        color: var(--app_primary);
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }

      .show-tag {
        margin: 0 10px 5px 0 !important;
      }
    }

    .el-dialog {
      .del-data {
        text-align: center;
        margin-bottom: 16px;

        img {
          width: 130px;
          height: 110px;
        }
      }

      .del-img {}
    }
  }
</style>
